package util;

import java.sql.*;

public class DBTool {

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     * @param sql
     * @return
     * @throws SQLException
     */
    public static Connection createConnection() throws SQLException {
        // 获取连接
        Connection conn = DriverManager.getConnection(Constants.URL,Constants.USERNAME,Constants.PASSWORD);
        return conn;
    }

    /**
     * 执行非查询语句并获取受影响的行数
     * @param sql
     * @return
     * @throws SQLException
     */
    public static int executeUpdate(String sql) throws SQLException {
        Connection conn = createConnection();
        Statement st = conn.createStatement();// 通过
        int count = st.executeUpdate(sql);
        closeStatement(st);
        closeConnection(conn);
        return count;
    }

    public static ResultSet executeQuery(String sql) throws SQLException {
        Connection conn = createConnection();
        Statement st = conn.createStatement();// 通过
        ResultSet rs = st.executeQuery(sql);
        return rs;
    }

    public static void closeResultSet(ResultSet rs){
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void closeStatement(Statement st){
        if(st != null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void closeConnection(Connection conn){
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
